﻿using System;
using System.ComponentModel;
using System.Threading;

namespace SIToFb2
{
  public class MessageCollection : ThreadedBindingList<Message>
  {
    public void Error(string text, params object[] args)
    {
      Error(string.Format(text, args));
    }

    public void Error(string text)
    {
      Add(new Message
            {
              MessageType = MessageType.Error,
              Text = text,
              Time = DateTime.Now
            });
    }

    public void Warning(string text, params object[] args)
    {
      Warning(string.Format(text, args));
    }

    public void Warning(string text)
    {
      Add(new Message
            {
              MessageType = MessageType.Warning,
              Text = text,
              Time = DateTime.Now
            });
    }

    public void Notification(string text, params object[] args)
    {
      Notification(string.Format(text, args));
    }

    public void Notification(string text)
    {
      Add(new Message
            {
              MessageType = MessageType.Notification,
              Text = text,
              Time = DateTime.Now
            });
    }
  }

  public class ThreadedBindingList<T> : BindingList<T>
  {
    SynchronizationContext ctx = SynchronizationContext.Current;
    protected override void OnAddingNew(AddingNewEventArgs e)
    {
      if (ctx == null)
      {
        BaseAddingNew(e);
      }
      else
      {
        ctx.Send(delegate { BaseAddingNew(e); }, null);
      }
    }

    void BaseAddingNew(AddingNewEventArgs e)
    {
      base.OnAddingNew(e);
    }

    protected override void OnListChanged(ListChangedEventArgs e)
    {
      //SynchronizationContext ctx = SynchronizationContext.Current;
      if (ctx == null)
      {
        BaseListChanged(e);
      }
      else
      {
        ctx.Send(delegate { BaseListChanged(e); }, null);
      }
    }

    void BaseListChanged(ListChangedEventArgs e)
    {
      base.OnListChanged(e);
    }
  }
}